package com.tuanzi.loan.business.repository.family.impl;

import static com.tuanzi.loan.generated.jooq.loan.tables.PayOrder.PAY_ORDER;

import java.util.*;

import com.tuanzi.server.loan_base.util.DateUtils;
import org.joda.time.DateTime;
import org.jooq.Result;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;

import com.tuanzi.loan.business.repository.family.PayRecordHourStatisticRepository;
import com.tuanzi.loan.core.repository.JOOQBaseRepositoryPlus;
import com.tuanzi.loan.vo.request.family.PayRecordHourStatisticSearchRequest;
import com.tuanzi.loan.vo.response.family.PayRecordHourStatisticSearchResponse;

@Repository
public class PayRecordHourStatisticRepositoryImpl extends JOOQBaseRepositoryPlus implements PayRecordHourStatisticRepository {
    /**
     * PayRecordHourStatistic查询
     *
     * @param searchRequest 请求信息
     * @param pageable      分页信息
     * @return 响应列表
     */
    @Override
    public Page<PayRecordHourStatisticSearchResponse> list(PayRecordHourStatisticSearchRequest searchRequest, Pageable pageable) {
        fields( PAY_ORDER.ENTRANCE,
                DSL.field("DATE(`create_time`)").as("create_date"),
                DSL.field("HOUR(`create_time`)").as("create_hour"),
                DSL.count(PAY_ORDER.ID).as("hour_count"));

        eq(PAY_ORDER.ORDER_STATUS,searchRequest.getPayState());
        ge(PAY_ORDER.CREATE_TIME,searchRequest.getStartTime() == null ? new DateTime().withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).toDate()
                : searchRequest.getStartTime());
        le(PAY_ORDER.CREATE_TIME,searchRequest.getEndTime());

        groupBy(DSL.field("create_date"));
        groupBy(PAY_ORDER.ENTRANCE);
        groupBy(DSL.field("create_hour"));

        orderBy(DSL.field("create_date"), Sort.Direction.DESC);
        orderBy(PAY_ORDER.ENTRANCE, Sort.Direction.ASC);

        List<PayRecordHourStatisticSearchResponse> responses = new ArrayList<>();
        Map<String,Map<String,PayRecordHourStatisticSearchResponse>> dateIndex = new HashMap<>();

        Result result = doNoPageableSearch();
        int size = result.size();
        for (int i = 0; i < size; i++) {
            String date = result.getValue(i, DSL.field("create_date")).toString();
            String entrance = result.getValue(i, PAY_ORDER.ENTRANCE) == null ?
                    "Unknown" : result.getValue(i, PAY_ORDER.ENTRANCE).toString();
            String hourStr = result.getValue(i, DSL.field("create_hour")).toString();
            String countStr = result.getValue(i, DSL.field("hour_count")).toString();
            Map<String, PayRecordHourStatisticSearchResponse> entranceIndex = dateIndex.get(date);
            if (entranceIndex == null){
                entranceIndex = new HashMap<>();
                dateIndex.put(date, entranceIndex);
            }
            PayRecordHourStatisticSearchResponse response = entranceIndex.get(entrance);
            if (response == null){
                response = new PayRecordHourStatisticSearchResponse();
                response.setDate(date);
                response.setEntrance(entrance);
                responses.add(response);
                entranceIndex.put(entrance,response);
            }
            try {
                int hour = Integer.parseInt(hourStr);
                int count = Integer.parseInt(countStr);
                response.getHourCountArray()[hour] = count;
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }

        if (pageable.getOffset() > 0 && pageable.getOffset() < responses.size())
            responses = responses.subList(pageable.getOffset(),responses.size() - 1);
        return new PageImpl<PayRecordHourStatisticSearchResponse>(responses, pageable, responses.size());
    }

    @Override
    protected TableImpl getTable() {
        return PAY_ORDER;
    }
}
